package handler

import (
	"content_system/router/middleware"
	"content_system/service"
	"content_system/value"
	"content_system/value/dto"
	"github.com/gin-gonic/gin"
	"net/http"
	"sync"
)

var (
	onceUserHandler sync.Once
	userHandler     *UserHandler
)

func GetUserHandler() *UserHandler {
	onceUserHandler.Do(func() {
		userHandler = &UserHandler{}
	})
	return userHandler
}

type UserHandler struct {
}

func (u *UserHandler) Register(g *gin.Context) {
	var req dto.UserRegisterRequest
	if err := g.ShouldBindBodyWithJSON(&req); err != nil {
		g.JSON(http.StatusBadRequest, value.Fail(400, err.Error()))
		return
	}
	resp, err := service.GetUserService().Register(g, &req)
	if err != nil {
		g.JSON(http.StatusInternalServerError, value.Fail(500, err.Error()))
		return
	}
	g.JSON(http.StatusOK, value.Success(resp))
	return
}

func (u *UserHandler) Login(g *gin.Context) {
	var req dto.UserLoginRequest
	if err := g.ShouldBindBodyWithJSON(&req); err != nil {
		g.JSON(http.StatusBadRequest, value.Fail(400, err.Error()))
		return
	}
	resp, err := service.GetUserService().Login(g, &req)
	if err != nil {
		g.JSON(http.StatusInternalServerError, value.Fail(500, err.Error()))
		return
	}
	g.JSON(http.StatusOK, value.Success(resp))
	return
}

func (u *UserHandler) Info(g *gin.Context) {
	uid, ok := g.Get(middleware.UserID)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	id, ok := uid.(int64)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	resp, err := service.GetUserService().Info(g, id)
	if err != nil {
		g.JSON(http.StatusInternalServerError, value.Fail(500, err.Error()))
		return
	}
	g.JSON(http.StatusOK, value.Success(resp))
	return
}
